package cn.jinbyte.data.service;


import cn.hutool.core.lang.UUID;
import cn.jinbyte.core.exception.BussException;
import cn.jinbyte.core.utils.Sm2Utils;
import cn.jinbyte.data.config.CryptProperties;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

/**
 * sm2服务
 */
public class Sm2Service {

    private final CacheService<String> cacheService;
    private final CryptProperties properties;

    public Sm2Service(CacheService<String> cacheService, CryptProperties properties) {
        this.cacheService = cacheService;
        this.properties = properties;
    }


    /**
     * 是否禁用SM2缓存
     *
     * @return true
     */
    public boolean isDisable() {
        return !properties.getSm2().isEnable();
    }

    /**
     * 生成sm2密钥对，缓存私钥，返回公钥
     *
     * @return java.util.Map<java.lang.String, java.lang.String>
     */
    public Map<String, String> createPublicKey() {
        Sm2Utils.KeyPair keyPair = Sm2Utils.createKeyPair();
        String publicId = UUID.fastUUID().toString(true);
        cacheService.set(properties.getSm2().getKeyPrefix() + publicId, keyPair.getPrivateKey(),
                properties.getSm2().getTimeout(), properties.getSm2().getTimeUnit());
        Map<String, String> map = Maps.newHashMap();
        map.put("publicId", publicId);
        map.put("publicKey", keyPair.getPublicKey());
        map.put("enabled", String.valueOf(properties.getSm2().isEnable()));
        return map;
    }

    /**
     * 根据缓存id获取私钥
     *
     * @param publicId 缓存id
     * @return java.lang.String
     * @throws BussException 公钥不存在
     */
    @NotNull
    public String getPrivateKey(String publicId) throws BussException {
        String privateKey = cacheService.get(properties.getSm2().getKeyPrefix() + publicId);
        if (StringUtils.isBlank(privateKey)) {
            throw new BussException("公钥不存在");
        }
        return privateKey;
    }
}
